package leetcode;

import org.springframework.util.Assert;

/**
 * @author yinlei
 * @date 2018/6/14
 * @since 1.0.0
 */
public class N003LongestSubstringWithoutRepeatingCharacters {
    public static void main(String[] args) {
        Solution2 solution2 = new Solution2();

        Assert.isTrue(solution2.lengthOfLongestSubstring("abcabcbb") == 3);
        Assert.isTrue(solution2.lengthOfLongestSubstring("bbbbb") == 1);
        Assert.isTrue(solution2.lengthOfLongestSubstring("pwwkew") == 3);
        Assert.isTrue(solution2.lengthOfLongestSubstring("a") == 1);
        Assert.isTrue(solution2.lengthOfLongestSubstring("ab") == 2);
        Assert.isTrue(solution2.lengthOfLongestSubstring("aab") == 2);
        Assert.isTrue(solution2.lengthOfLongestSubstring("tmmzuxt") == 5);
        Assert.isTrue(solution2.lengthOfLongestSubstring("bbtablud") == 6);
    }

    static class Solution2 {
        public int lengthOfLongestSubstring(String s) {
            int bigLength = 0;
            char[] array = s.toCharArray();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; i++) {
                int index = sb.indexOf(String.valueOf(array[i]));
                if (index != -1) {
                    //说明包含
                    String after = sb.substring(index, sb.length());
                    i = i - 1 - after.length() + 1;
                    if (bigLength < sb.length()) {
                        bigLength = sb.length();
                    } else if (bigLength == sb.length()) {
                    }
                    sb = new StringBuffer();
                } else {
                    sb.append(array[i]);
                }
            }
            if (sb.length() > bigLength) {
                bigLength = sb.length();
            }
            return bigLength;
        }
    }

}
